package com.wsoft.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wsoft.constant.redis.RedisKeyConstant;
import com.wsoft.core.annotation.GetRedisCache;
import com.wsoft.core.annotation.InitRedisCache;
import com.wsoft.core.service.CommonOrgService;
import com.wsoft.core.service.RedisService;
import com.wsoft.core.vo.OrganizationVO;
import com.wsoft.entity.BaseEntity;
import com.wsoft.system.dto.SysMemberOrgRoleRelationDTO;
import com.wsoft.system.entity.SysAccountEntity;
import com.wsoft.system.entity.SysMemberEntity;
import com.wsoft.system.entity.SysMemberOrgRoleRelationEntity;
import com.wsoft.system.mapper.SysMemberMapper;
import com.wsoft.system.mapper.SysMemberOrgRoleRelationMapper;
import com.wsoft.system.query.member.MemberOrgRoleQuery;
import com.wsoft.system.service.ISysAccountService;
import com.wsoft.system.service.ISysMemberOrgRoleRelationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wsoft.system.service.ISysRoleService;
import com.wsoft.vo.MemberOrgRoleRespVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 人员组织用户关联表 服务实现类
 * </p>
 *
 * @author zhonglj
 * @since 2024年09月06日 14:06:45
 */
@Service
public class SysMemberOrgRoleRelationServiceImpl extends ServiceImpl<SysMemberOrgRoleRelationMapper, SysMemberOrgRoleRelationEntity> implements ISysMemberOrgRoleRelationService {

    @Resource
    private ISysRoleService sysRoleService;
    @Resource
    private SysMemberMapper memberMapper;
    @Resource
    private SysMemberOrgRoleRelationMapper sysMemberOrgRoleRelationMapper;
    @Resource
    private ISysAccountService accountService;
    @Resource
    private RedisService redisService;
    @Resource
    private CommonOrgService commonOrgService;
    @Override
    @InitRedisCache(type = RedisKeyConstant.MEMBER_ROLE_CACHE,
            value = "memberId")
    @Transactional(rollbackFor = Exception.class)
    public void insertRelationByMemberId(MemberOrgRoleQuery query) {
        // 增加组织角色关系
        for (SysMemberOrgRoleRelationDTO re : query.getRelations()) {
            for (Long roleId : re.getRoleIds()) {
                SysMemberOrgRoleRelationEntity entity = new SysMemberOrgRoleRelationEntity();
                entity.setMemberId(query.getMemberId());
                entity.setOrgId(re.getOrgId());
                entity.setRoleId(roleId);
                save(entity);
            }
                    Long curOrgId = query.getRelations().get(0).getOrgId();
                    QueryWrapper<SysAccountEntity> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(SysAccountEntity::getMemberId,query.getMemberId());
                    SysAccountEntity account = accountService.getOne(queryWrapper);
                    OrganizationVO orgInfo = commonOrgService.getOrgInfo(curOrgId);
                    memberMapper.update(Wrappers
                            .lambdaUpdate(SysMemberEntity.class)
                            .set(SysMemberEntity::getCurOrgId, curOrgId)
                            .set(SysMemberEntity::getLoginOrgId, orgInfo.getOrgId())
                            .set(SysMemberEntity::getLoginOrgCode, orgInfo.getCode())
                            .set(SysMemberEntity::getLoginOrgName, orgInfo.getName())
                            .eq(BaseEntity::getId, query.getMemberId())
                    );
                    //清除用户信息缓存
                    redisService.del(RedisKeyConstant.USER_INFO_CACHE + account.getLoginName());
            }
        }

    @Override
    @InitRedisCache(type = RedisKeyConstant.MEMBER_ROLE_CACHE,
            value = "memberId")
    @Transactional(rollbackFor = Exception.class)
    public void updateRelationByMemberId(MemberOrgRoleQuery query) {
        //清空关系
        deleteByMemberId(query.getMemberId());
        //重新绑定
        insertRelationByMemberId(query);
    }

//    @Override
//    public List<SysRoleEntity> getRoleListByMember(Long memberId) {
//        QueryWrapper<SysMemberOrgRoleRelationEntity> query = new QueryWrapper<>();
//        query.lambda().eq(SysMemberOrgRoleRelationEntity::getMemberId,memberId)
//        List<SysMemberOrgRoleRelationEntity> list = list(query);
//        if (list != null && list.size() > 0) {
//            List<Long> roleIds = list.stream().map(SysMemberOrgRoleRelationEntity::getRoleId).collect(Collectors.toList());
//            return sysRoleService.listByIds(roleIds);
//        }
//        return new ArrayList<>();
//    }

    @Override
    @GetRedisCache(type = RedisKeyConstant.MEMBER_ROLE_CACHE,
            value = RedisKeyConstant.REDIS_SELF)
    public List<MemberOrgRoleRespVO> getRelationByMember(Long memberId) {
        // 加载所有关联组织链环境配置
        List<SysMemberOrgRoleRelationEntity> orgRoleRelations = sysMemberOrgRoleRelationMapper.selectList(Wrappers
                .lambdaQuery(SysMemberOrgRoleRelationEntity.class)
                .eq(SysMemberOrgRoleRelationEntity::getMemberId, memberId)
        );
        List<MemberOrgRoleRespVO> relations = new ArrayList<>();
        if (CollUtil.isNotEmpty(orgRoleRelations)) {
            Map<Long, List<SysMemberOrgRoleRelationEntity>> orgMap = orgRoleRelations.stream().collect(Collectors.groupingBy(SysMemberOrgRoleRelationEntity::getOrgId));
            for (Map.Entry<Long, List<SysMemberOrgRoleRelationEntity>> each : orgMap.entrySet()) {
                MemberOrgRoleRespVO respVO = new MemberOrgRoleRespVO();
                Long orgId = each.getKey();
                respVO.setOrgId(orgId);
                List<Long> roleIds = each.getValue().stream().filter(item -> item.getRoleId()!=null).map(SysMemberOrgRoleRelationEntity::getRoleId).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(roleIds)){
                    respVO.setRoleIds(roleIds);
                }
                relations.add(respVO);
            }
        }
        return relations;
    }

    private void deleteByMemberId(Long memberId){
        QueryWrapper<SysMemberOrgRoleRelationEntity> query = new QueryWrapper<>();
        query.lambda().eq(SysMemberOrgRoleRelationEntity::getMemberId,memberId);
        remove(query);
    }
}
